<!-- 用车调度 -->
<template>
  <div class="app-container">
    <!-- 表格状态切换按钮 -->
    <ul class="nav">
      <li v-for="v in navData" :class="{ active: v.value == queryParams.dispatchOrderStatus }" @click="navChangeHandle(v.value)">
        {{ v.label }}
      </li>
    </ul>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <searchType v-for="v in searchProps" :data="v" :selects="sel_option[v.prop]" v-model="queryParams[v.prop]"
        :handleQuery="handleQuery">
      </searchType>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['gwc:vehicles:add']">申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" v-hasPermi="['gwc:vehicles:edit']">补单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['gwc:vehicles:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['gwc:vehicles:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehiclesList" @selection-change="handleSelectionChange">
      <el-table-column :label="v.label" align="center" :prop="v.prop" :width="v.width" v-for="v in tableProps">
        <template #default="scope">
          <span v-if="v.prop == 'destination'">{{ scope.row[v.prop].map(v => v.address).join(',') }}</span>
          <dict-tag v-else-if="v.prop == 'purpose'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleDispach(scope.row, false)" v-show="queryParams.dispatchOrderStatus == '1'"
            v-hasPermi="['gwc:vehicles:edit']">调度</el-button>
          <el-button link type="primary" @click="stopDispatch(scope.row)" v-show="queryParams.dispatchOrderStatus == '1'"
            v-hasPermi="['gwc:vehicles:remove']">终止调度</el-button>
          <el-button link type="primary" @click="handleDispach(scope.row, true)" v-show="queryParams.dispatchOrderStatus == '2'"
            v-hasPermi="['gwc:vehicles:remove']">调度转派</el-button>
          <el-button link type="primary" @click="dispatchDetail(scope.row)" v-show="queryParams.dispatchOrderStatus == '2'"
            v-hasPermi="['gwc:vehicles:remove']">调度详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 调度车辆详情 -->
    <el-dialog title="调度车辆详情" v-model="open" width="800px" append-to-body>
      <el-table :data="form.selects" style="height: 600px;">
        <el-table-column label="序号" align="center" type="index" :width="55"> </el-table-column>
        <el-table-column :label="v.label" align="center" :prop="v.prop" :width="v.width" v-for="v in detailTableProps">
          <template #default="scope">
            <dict-tag v-if="v.prop == 'purpose'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
            <span v-else>{{ scope.row[v.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <el-dialog title="调派车辆" v-model="dispachOpen" append-to-body :destroy-on-close="true">
      <carDriverSelect v-model="form.selects" :vehicleNum="form.vehicleNum"></carDriverSelect>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dispachSubmit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Vehicles" lang="ts">
import { getApplication, delApplication, addApplication, updateApplication } from "@/api/gwc/application";
import { delVehicles, addVehicles, updateVehicles, listVehicles, listReviewVehicles } from "@/api/gwc/vehicles";
import searchType from "@/components/tableRelate/searchType.vue";
import { searchComponentType } from "@/components/tableRelate/searchTypeTs"
import { getSearchCompanyListRole } from "@/api/system/dept";
import dayjs from "dayjs"
const { proxy } = getCurrentInstance() as any;

const vehiclesList = ref([]);
const open = ref(false);
const dispachOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sel_option = ref<any>({});
const treeList = ref([])

let onceAgain = false;
getSearchCompanyListRole().then(res => {
  treeList.value = res.data
})

const navData = reactive([
  { label: "待调度", value: "1" },
  { label: "已调度", value: "2" },
])

const searchProps = reactive([
  { label: "用车人姓名", prop: "2", type: searchComponentType.input },
  { label: "申请时间", prop: "1", type: searchComponentType.dateTime },
]);
const tableProps = ref([
  { label: "用车人姓名", prop: "useName", width: "120" },
  { label: "用车人电话", prop: "useTel", width: "120" },
  { label: "申请人姓名", prop: "applyName", width: "120" },
  { label: "申请人电话", prop: "applyTel", width: "120" },
  { label: "所属部门", prop: "companyName", width: "120" },
  { label: "用途", prop: "purpose", width: "120", type: 'dict' },
  { label: "用车人数", prop: "userNum", width: "120" },
  { label: "上车地点", prop: "boardingLocation", width: "120" },
  { label: "目的地", prop: "destination", width: "120" },
  { label: "用车数量", prop: "vehicleNum", width: "120" },
  { label: "申请时间", prop: "createTime", width: "180" },
  { label: "用车时间", prop: "boardingTime", width: "180" },
  { label: "返程时间", prop: "returnTime", width: "180" },
])
const detailTableProps = reactive([
  { label: "司机名称", prop: "driverName", width: "140" },
  { label: "车牌号", prop: "numberPlate", width: "120" },
  { label: "联系方式", prop: "contactNumber", width: "140" },
  { label: "公司名称", prop: "companyName" },
])
const data = reactive({
  form: {} as any,
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    applyId: null,
    companyId: null,
    driverId: null,
    vehicleId: null,
    remarks: null,
    dispatchOrderStatus: "1",
  },
  rules: {
    applyId: [
      { required: true, message: "申请单id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
let dictList = tableProps.value.filter(v => v.type == 'dict').map(v => v.prop);
sel_option.value = proxy.useDict.apply(this, [...dictList]);
function navChangeHandle(val) {
  queryParams.value.dispatchOrderStatus = val;
  handleQuery();
}
proxy.setValidateByTable(rules, detailTableProps);

/** 查询调度车辆列表 */
function getList() {
  loading.value = true;
  listReviewVehicles(queryParams.value).then((response: any) => {
    vehiclesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  dispachOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
  };
  proxy.resetForm("vehiclesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.applyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleDispach(row, bool) {
  onceAgain = bool;
  reset();
  listVehicles({ applyId: row.applyId }).then((response: any) => {
    form.value = JSON.parse(JSON.stringify(row))
    form.value.selects = response.rows;
    dispachOpen.value = true;
    title.value = "调度车辆";
  });
}

function dispatchDetail(row) {
  listVehicles({ applyId: row.applyId }).then((response: any) => {
    form.value.selects = response.rows;
    open.value = true
  });
}

function dispachSubmit() {
  if (form.value.vehicleNum != form.value.selects.length) {
    proxy.$modal.msgWarning("用车数量不匹配！");
    return
  }
  const res = form.value.selects.map(v => {
    return {
      applyId: form.value.applyId,
      ...v
    }
  })
  if (onceAgain) {
    updateVehicles(res).then(response => {
      proxy.$modal.msgSuccess("转派调度成功");
      cancel();
      getList();
    });
  } else {
    addVehicles(res).then(response => {
      proxy.$modal.msgSuccess("调度成功");
      cancel();
      getList();
    });
  }

}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dispatchIds = row.applyId || ids.value;
  proxy.$modal.confirm('是否确认删除调度车辆编号为"' + _dispatchIds + '"的数据项？').then(function () {
    return delVehicles(_dispatchIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

function stopDispatch(row) {
  const _dispatchIds = row.applyId || ids.value;
  proxy.$modal.confirm('是否确认终止调度车辆编号为"' + _dispatchIds + '"的数据项？').then(function () {
    return updateApplication({
      orderStatus: 6,
      applyId: _dispatchIds,
    });
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("终止成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('gwc/vehicles/export', {
    ...queryParams.value
  }, `用车调度_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}

getList();
</script>
<style scoped lang="scss">
.textarea,
.destination,
.photo {
  display: block-flex !important;
  display: flex !important;
  width: calc(100% - 64px)
}

.disableClass {
  :deep(.item-actions) {
    opacity: 0 !important;
  }
}

:deep(.apply-window) {
  margin-top: 30vh;
}
</style>